import { observer } from "./observer/index.js";
import Watcher from "./observer/watcher.js";
function Vue(options) {
  const vm = this;
  vm.$options = options;
  vm._data = typeof options.data === "function" ? options.data() : options.data;
  _initData.call(vm);
  const watch = vm.$options.watch;
  // watch 选项的实现
  if (watch) {
    let keys = Object.keys(watch);
    for (let i = 0; i < keys.length; i++) {
      // 实现watch 并执行回调
      new Watcher(vm, keys[i], watch[keys[i]]);
    }
  }
  initComputed(vm);
}

// $watch方法的实现
Vue.prototype.$watch = function (key, cb) {
  // 实现watch 并执行回调
  const vm = this;
  new Watcher(vm, key, cb);
};

// 数据代理
function _proxy(data) {
  const _this = this;
  Object.keys(data).forEach((key) => {
    Object.defineProperty(_this, key, {
      get() {
        return data[key];
      },
      set(newValue) {
        data[key] = newValue;
      },
    });
  });
}

// 优化代码结构
function _initData() {
  const vm = this;
  observer(vm._data);
  // 将数据代理到实例身上，可以通过实例直接访问数据
  _proxy.call(vm, vm._data);
}

// 分离计算属性实现方法逻辑
function initComputed(vm) {
  let computed = vm.$options.computed;
  console.log("computed :>> ", computed);
  if (computed) {
    let keys = Object.keys(computed);
    for (let i = 0; i < keys.length; i++) {
      const watcher = new Watcher(vm, computed[keys[i]], () => {}, {
        lazy: true,
      });
      Object.defineProperty(vm, keys[i], {
        enumerable: true,
        configurable: true,
        get() {
          if (watcher.dirty) {
            watcher.value = watcher.get();
            watcher.dirty = false;
          }
          return watcher.value;
        },
        set() {
          console.log("computed不能赋值");
        },
      });
    }
  }
}

export default Vue;
